package com.winit.openapi.fna.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.SearchOperator;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.query.filter.SearchFilterHelper;
import com.winit.common.spi.SPIException;
import com.winit.common.spi.context.CommandContext;
import com.winit.fna.spi.fundTransaction.CustomerAccountLineService;
import com.winit.fna.spi.fundTransaction.command.ExportCustomerAccountLineExcelCommand;
import com.winit.fna.spi.reportManager.ReportManagementService;
import com.winit.fna.spi.reportManager.command.QueryReportManagementListCommand;
import com.winit.fna.spi.reportManager.vo.ReportManagement;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.ValidateUtil;

/**
 * 报表管理 <Change to the actual description of this class>
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * jian.ma 	1.0  		2015年8月24日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping("/fna/reportManagement")
public class ReportManagementContrller extends BaseController {

    @Resource
    private ReportManagementService    reportManagementService;
    @Resource
    private CustomerAccountLineService customerAccountLineService;

    /**
     * 报表管理列表 TODO Add comments here.
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/page")
    public String pageQueryReportManagement(@ModelAttribute RequestMsg requestMsg,
                                            @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        QueryReportManagementListCommand command = new QueryReportManagementListCommand();
        CommandContext ctx = CommandContext.getContext();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            validpageParams(json);
            try {
                command = JSONObject.toJavaObject(json, QueryReportManagementListCommand.class);
                Searchable searchable = buildSearchPageParams(json);
                searchable.addSort(new Sort(Direction.DESC, "CREATED"));
                if ("0".equals(command.getReportContent())) {
                    searchable.and(SearchFilterHelper.newCondition("REPORT_CONTENT",
                        SearchOperator.ne,"3"));
                }
                else {
                	if (StringUtils.isNotBlank(command.getReportContent())) {
                		 searchable.and(SearchFilterHelper.newCondition("REPORT_CONTENT",
                                 SearchOperator.eq,
                                 command.getReportContent()));
                	}
                }
                searchable.and(SearchFilterHelper.newCondition("WT_BPARTNER_ID", SearchOperator.eq, ctx.getUserId()));
                command.setSearchable(searchable);
                command.setCtx(ctx);
                Page<ReportManagement> page = reportManagementService.queryReportManagement(command);
                if (page != null) {
                    Map<String, Object> pageMap = new HashMap<String, Object>();
                    pageMap.put("pageNo", page.getPageable().getPageNumber() + 1);
                    pageMap.put("pageSize", page.getPageable().getPageSize());
                    pageMap.put("totalCount", page.getTotalElements());

                    Map<String, Object> data = new HashMap<String, Object>();
                    data.put("list", page.getContent());
                    data.put("pageParams", pageMap);
                    responseMsg.setData(data);
                }

            } catch (SPIException e) {
                throw new SPIException("javaBean 转换错误");
            }

        } else {
            throw new SPIException("json 格式错误");
        }

        return SUCCESS;
    }

    /**
     * 导出操作记录 TODO Add comments here.
     * 
     * @return
     */
    @RequestMapping("exportOperationRecord")
    public String exportOperationRecord(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ExportCustomerAccountLineExcelCommand command = new ExportCustomerAccountLineExcelCommand();
            buildExportSearchableAndCommand(json, command);
            customerAccountLineService.exportCustomerAccountLineExcel(command);
        } else {
            throw new SPIException("json 格式错误");
        }

        return SUCCESS;
    }

    private void buildExportSearchableAndCommand(JSONObject json, ExportCustomerAccountLineExcelCommand command) {
        if (json != null && json.containsKey("startDate")) {
            String start = json.getString("startDate");
            start += " 00:00:00";
            Date startDate = DateUtil.parse2Date(start, DateUtil.FULL_DATE_STRING);
            command.setStartDate(startDate);
        }
        if (json != null && json.containsKey("endDate")) {
            String end = json.getString("endDate");
            end += " 23:59:59";
            Date endDate = DateUtil.parse2Date(end, DateUtil.FULL_DATE_STRING);
            command.setEndDate(endDate);
        }
    }

    private void validpageParams(JSONObject json) {
        // pageParams
        if (json.containsKey("pageParams")) {
            Object obj = json.get("pageParams");
            if (obj instanceof JSONObject) {
                JSONObject pageParams = (JSONObject) obj;
                // pageNo
                ValidateUtil.validInteger(pageParams, "pageNo");
                // pageSize
                ValidateUtil.validInteger(pageParams, "pageSize");
                if (pageParams.containsKey("pageNo")) {
                    int pageNo = pageParams.getInteger("pageNo");
                    if (pageNo < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageNo");
                    }
                }
                if (pageParams.containsKey("pageSize")) {
                    int pageSize = pageParams.getInteger("pageSize");
                    if (pageSize < 1) {
                        throw new ApiException(ErrorCode.FIELD_ERROR, "pageSize");
                    }
                }
            } else {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageParams");
            }
        }
    }

    private Searchable buildSearchPageParams(JSONObject json) {
        int pageNo = ApiConstant.PAGE_NO_DEFAULT;
        int pageSize = ApiConstant.PAGE_SIZE_DEFAULT;
        // pageParams
        if (json != null && json.containsKey("pageParams")) {
            JSONObject pageParams = json.getJSONObject("pageParams");
            // pageNo
            if (pageParams.containsKey("pageNo")) {
                pageNo = pageParams.getInteger("pageNo");
            }
            // pageSize
            if (pageParams.containsKey("pageSize")) {
                pageSize = pageParams.getInteger("pageSize");
            }
        }
        Searchable search = Searchable.newSearchable();
        search.setPage(pageNo - 1, pageSize);
        search.addSort(new Sort(Direction.DESC, "CREATED"));
        return search;
    }
}
